import type { Device, StreamServer } from '@/types'

/**
 * 从流路径中提取流名称
 * @param streamPath 流路径，如 "/jtlive/jt_n127000000001_c84_s0.flv" 或 "/hls/jt_n127000000001_c84_s0/index.m3u8"
 * @param streamType 流类型
 * @returns 提取的流名称，如 "jt_n127000000001_c84_s0"
 */
function extractStreamName(streamPath: string, streamType: 'flv' | 'flvsub' | 'hls' | 'hlssub'): string {
  if (!streamPath) return ''
  
  // 去掉开头的斜杠
  const cleanPath = streamPath.startsWith('/') ? streamPath.substring(1) : streamPath
  
  if (streamType === 'flv' || streamType === 'flvsub') {
    // FLV流路径格式: "jtlive/jt_n127000000001_c84_s0.flv"
    // 提取文件名并去掉扩展名
    const fileName = cleanPath.split('/').pop() || ''
    return fileName.replace(/\.flv$/, '')
  } else if (streamType === 'hls' || streamType === 'hlssub') {
    // HLS流路径格式: "hls/jt_n127000000001_c84_s0/index.m3u8"
    // 提取目录名
    const pathParts = cleanPath.split('/')
    if (pathParts.length >= 2) {
      return pathParts[1] // 返回 "jt_n127000000001_c84_s0"
    }
    return pathParts[0] || ''
  }
  
  return cleanPath
}

/**
 * 根据设备信息和服务器信息构建完整的流地址
 */
export function buildStreamUrl(
  device: Device, 
  server: StreamServer, 
  streamType: 'flv' | 'flvsub' | 'hls' | 'hlssub'
): string

/**
 * 根据设备信息、服务器列表和流类型构建完整的流地址
 */
export function buildStreamUrl(
  device: Device, 
  servers: StreamServer[], 
  streamType: 'flv' | 'flvsub' | 'hls' | 'hlssub'
): string

export function buildStreamUrl(
  device: Device, 
  serverOrServers: StreamServer | StreamServer[], 
  streamType: 'flv' | 'flvsub' | 'hls' | 'hlssub'
): string {
  // 确定服务器对象
  let server: StreamServer | null = null
  
  if (Array.isArray(serverOrServers)) {
    // 从服务器列表中查找
    server = serverOrServers.find(s => s.id === device.nvrId) || null
  } else {
    // 直接使用传入的服务器
    server = serverOrServers
  }
  
  if (!server) {
    console.warn(`No server found for device ${device.id} (nvrId: ${device.nvrId})`)
    return ''
  }
  
  const streamPath = device[streamType]
  
  if (!streamPath) {
    console.warn(`Device ${device.id} has no ${streamType} stream path`)
    return ''
  }
  
  // 提取流名称
  const streamName = extractStreamName(streamPath, streamType)
  
  // 构建完整URL
  return `http://${server.ip}:${server.streamPort}/live?port=1935&app=hls&stream=${streamName}`
}

/**
 * 为设备构建所有流地址
 */
export function buildAllStreamUrls(device: Device, server: StreamServer): {
  flv: string
  flvsub: string
  hls: string
  hlssub: string
} {
  return {
    flv: buildStreamUrl(device, server, 'flv'),
    flvsub: buildStreamUrl(device, server, 'flvsub'),
    hls: buildStreamUrl(device, server, 'hls'),
    hlssub: buildStreamUrl(device, server, 'hlssub')
  }
}

/**
 * 根据nvrId从服务器列表中查找对应的服务器
 */
export function findServerByNvrId(servers: StreamServer[], nvrId: number): StreamServer | null {
  const server = servers.find(s => s.id === nvrId)
  if (!server) {
    console.warn(`No server found for nvrId: ${nvrId}`)
  }
  return server || null
}

/**
 * 处理设备列表，为每个设备构建完整的流地址
 */
export function processDevicesWithStreamUrls(devices: Device[], servers: StreamServer[]): Device[] {
  return devices.map(device => {
    const server = findServerByNvrId(servers, device.nvrId)
    
    if (!server) {
      console.warn(`No server found for device ${device.id} (nvrId: ${device.nvrId})`)
      return device
    }
    
    // 构建完整的流地址
    const streamUrls = buildAllStreamUrls(device, server)
    
    // 返回更新后的设备信息
    return {
      ...device,
      flv: streamUrls.flv,
      flvsub: streamUrls.flvsub,
      hls: streamUrls.hls,
      hlssub: streamUrls.hlssub
    }
  })
}

/**
 * 为搜索设备构建完整的流地址工具
 * 专门用于处理搜索结果中的设备流地址构建
 */
export function buildSearchDeviceStreamUrl(
  device: Device, 
  servers: StreamServer[], 
  streamType: 'flv' | 'flvsub' = 'flv'
): string {
  // 查找对应的服务器
  const server = findServerByNvrId(servers, device.nvrId)
  
  if (!server) {
    console.warn(`No server found for search device ${device.id} (nvrId: ${device.nvrId})`)
    return ''
  }
  
  // 使用现有的buildStreamUrl函数构建完整地址
  return buildStreamUrl(device, server, streamType)
}

/**
 * 为搜索设备列表构建完整的流地址
 * 批量处理搜索结果中的设备流地址
 */
export function buildSearchDevicesStreamUrls(
  devices: Device[], 
  servers: StreamServer[]
): Device[] {
  return devices.map(device => {
    const server = findServerByNvrId(servers, device.nvrId)
    
    if (!server) {
      console.warn(`No server found for search device ${device.id} (nvrId: ${device.nvrId})`)
      return device
    }
    
    // 构建完整的流地址
    const streamUrls = buildAllStreamUrls(device, server)
    
    // 返回更新后的设备信息，优先使用flv流
    return {
      ...device,
      flv: streamUrls.flv,
      flvsub: streamUrls.flvsub,
      hls: streamUrls.hls,
      hlssub: streamUrls.hlssub
    }
  })
}
